<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场所名称" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          placeholder="请输入场所名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in dict.type.device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备型号" prop="deviceModel">
        <el-select v-model="queryParams.deviceModel" placeholder="请选择设备型号" clearable>
          <el-option
            v-for="dict in dict.type.device_model"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['device:device:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['device:device:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['device:device:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['device:device:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceId" min-width="120" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="100" />
      <el-table-column label="场所名称" align="center" prop="locationName" min-width="120" />
      <el-table-column label="场所地址" align="center" prop="locationAddress" min-width="180" show-overflow-tooltip />
      <el-table-column label="联系人" align="center" prop="contactPerson" min-width="80" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="120" />
      <el-table-column label="设备型号" align="center" prop="deviceModel" min-width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_model" :value="scope.row.deviceModel" />
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" prop="ipAddress" min-width="120" />
      <el-table-column label="设备状态" align="center" prop="status" min-width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="最后心跳时间" align="center" prop="lastHeartbeat" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastHeartbeat, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装日期" align="center" prop="installDate" min-width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前在线" align="center" min-width="100">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.currentConnections || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="今日连接" align="center" min-width="100">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.todayConnections || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告策略" align="center" min-width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.adStrategy" type="success">{{ scope.row.adStrategy }}</el-tag>
          <el-tag v-else type="warning">未配置</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['device:device:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['device:device:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-hasPermi="['device:device:query']"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            v-hasPermi="['device:device:qrcode']"
            size="mini"
            type="text"
            icon="el-icon-picture-outline"
            @click="handleQrCode(scope.row)"
          >二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-data-line"
            @click="handleConnectionLog(scope.row)"
          >连接记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入设备ID" :disabled="form.deviceId && title.indexOf('修改') !== -1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="场所名称" prop="locationName">
              <el-input v-model="form.locationName" placeholder="请输入场所名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-select v-model="form.deviceModel" placeholder="请选择设备型号">
                <el-option
                  v-for="dict in dict.type.device_model"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="场所地址" prop="locationAddress">
          <el-input v-model="form.locationAddress" placeholder="请输入场所地址" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="MAC地址" prop="macAddress">
              <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker
                v-model="form.installDate"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择安装日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="title.indexOf('修改') !== -1" label="设备状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.device_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="设备密钥" prop="secretKey">
          <el-input v-model="form.secretKey" placeholder="请输入设备鉴权密钥" />
        </el-form-item>
        <el-form-item label="SN序列号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入SN序列号" />
        </el-form-item>

        <!-- WiFi配置区域 -->
        <el-divider content-position="left">WiFi配置</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="WiFi名称1" prop="wifiSsid">
              <el-input v-model="form.wifiSsid" placeholder="请输入WiFi网络名称(SSID)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="WiFi名称2" prop="wifiSsid2">
              <el-input v-model="form.wifiSsid2" placeholder="请输入第二个WiFi网络名称(SSID)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="WiFi密码" prop="wifiPassword">
              <el-input v-model="form.wifiPassword" placeholder="请输入WiFi密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全类型" prop="wifiSecurityType">
              <el-select v-model="form.wifiSecurityType" placeholder="请选择WiFi安全类型">
                <el-option label="开放网络" :value="0" />
                <el-option label="WPA/WPA2" :value="1" />
                <el-option label="WEP" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="WiFi频段" prop="wifiFrequency">
              <el-select v-model="form.wifiFrequency" placeholder="请选择WiFi频段">
                <el-option label="2.4GHz" :value="2.4" />
                <el-option label="5.0GHz" :value="5.0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信号强度" prop="wifiSignalStrength">
              <el-input v-model="form.wifiSignalStrength" placeholder="请输入信号强度(dBm)" />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                信号强度范围：-30dBm(强) 到 -90dBm(弱)
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="WiFi状态" prop="wifiEnabled">
              <el-radio-group v-model="form.wifiEnabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备详情对话框 -->
    <el-dialog title="设备详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备ID">{{ deviceDetail.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ deviceDetail.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="场所名称">{{ deviceDetail.locationName }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">
          <dict-tag :options="dict.type.device_model" :value="deviceDetail.deviceModel" />
        </el-descriptions-item>
        <el-descriptions-item label="场所地址" :span="2">{{ deviceDetail.locationAddress }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ deviceDetail.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ deviceDetail.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="MAC地址">{{ deviceDetail.macAddress }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ deviceDetail.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <dict-tag :options="dict.type.device_status" :value="deviceDetail.status" />
        </el-descriptions-item>
        <el-descriptions-item label="安装日期">{{ parseTime(deviceDetail.installDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="最后心跳时间" :span="2">{{ parseTime(deviceDetail.lastHeartbeat, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="经度">{{ deviceDetail.longitude }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ deviceDetail.latitude }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ parseTime(deviceDetail.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 二维码显示对话框 -->
    <el-dialog title="设备二维码" :visible.sync="qrCodeOpen" width="500px" append-to-body>
      <div style="text-align: center;">
        <el-image
          v-if="qrCodeImage"
          :src="qrCodeImage"
          style="width: 300px; height: 300px;"
          fit="contain"
        />
        <div style="margin-top: 20px; padding: 15px; background: #f5f7fa; border-radius: 8px;">
          <p><strong>设备ID:</strong> {{ currentDeviceId }}</p>
          <p><strong>场所名称:</strong> {{ currentDeviceInfo.locationName }}</p>
          <p><strong>二维码内容:</strong> deviceId={{ currentDeviceId }}</p>
          <p style="color: #909399; font-size: 12px;">用户扫描此二维码将启动小程序并传入设备参数</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadQrCode">下载二维码</el-button>
        <el-button @click="qrCodeOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, generateQrCode } from '@/api/wifi/device'

export default {
  name: 'Device',
  dicts: ['device_status', 'device_model'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 是否显示二维码弹出层
      qrCodeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        deviceName: null,
        locationName: null,
        deviceModel: null,
        status: null
      },
      // 表单参数
      form: {},
      // 设备详情
      deviceDetail: {},
      // 二维码图片
      qrCodeImage: null,
      // 当前设备ID
      currentDeviceId: null,
      // 当前设备信息
      currentDeviceInfo: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: '设备ID不能为空', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        locationName: [
          { required: true, message: '场所名称不能为空', trigger: 'blur' }
        ],
        contactPhone: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        macAddress: [
          { pattern: /^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$/, message: '请输入正确的MAC地址', trigger: 'blur' }
        ],
        ipAddress: [
          { pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入正确的IP地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询设备信息列表 */
    getList() {
      this.loading = true
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceName: null,
        locationName: null,
        locationAddress: null,
        contactPerson: null,
        contactPhone: null,
        deviceModel: null,
        macAddress: null,
        ipAddress: null,
        status: 1,
        lastHeartbeat: null,
        installDate: null,
        longitude: null,
        latitude: null,
        secretKey: null,
        sn: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改设备信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null && this.title.indexOf('修改') !== -1) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids
      this.$modal.confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevice(deviceIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    /** 设备详情 */
    handleDetail(row) {
      this.deviceDetail = row
      this.detailOpen = true
    },
    /** 生成二维码 */
    handleQrCode(row) {
      this.currentDeviceId = row.deviceId
      this.currentDeviceInfo = row
      generateQrCode(row.deviceId).then(response => {
        this.qrCodeImage = response.data
        this.qrCodeOpen = true
      })
    },
    /** 下载二维码 */
    downloadQrCode() {
      const link = document.createElement('a')
      link.href = this.qrCodeImage
      link.download = `device_${this.currentDeviceId}_qrcode.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    /** 连接记录 */
    handleConnectionLog(row) {
      this.$router.push('/wifi/connection-log/index?deviceId=' + row.deviceId)
    }
  }
}
</script>
